package cn.edu.ldu.util;

import cn.edu.ldu.http.rqtUtils;
import cn.edu.ldu.views.modules.entity.UserIpEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.scene.input.DataFormat;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Util {

    public static String MD5(String sourceStr) {
        try {
            // 获得MD5摘要算法的 MessageDigest对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(sourceStr.getBytes());
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            StringBuffer buf = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int tmp = md[i];
                if (tmp < 0)
                    tmp += 256;
                if (tmp < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(tmp));
            }
            //return buf.toString().substring(8, 24);// 16位加密
            return buf.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static UserIpEntity getIpInfo(InetAddress address){
        try {
            URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + address.getHostAddress());
            HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
            urlCon.connect();
            InputStream inputStream = urlCon.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String s = bufferedReader.readLine();
            inputStream.close();
            return JSONObject.parseObject(JSONObject.parseObject(s).getString("data"), UserIpEntity.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    private static String getCity(JSONObject jsonObject){
//        jsonObject.getJSONObject("data").getString("city")
//    }

    public static String nowDate(){
        Date date = Calendar.getInstance().getTime();
        return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.SIMPLIFIED_CHINESE).format(date);
    }

    public static String formatData(Date date){
        return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.SIMPLIFIED_CHINESE).format(date);
    }

}
